import JsEncrypt from 'jsencrypt'
import { KJUR, KEYUTIL, hex2b64 } from 'jsrsasign'
import Vue from 'vue'
import { Notify } from 'vant'
var RSAEncrypt = {
  // 公钥
  publicKey: `-----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmkpXILKab5JZglcgE1NHSCrcxIQwNvFnTPyHsOd9hqXTap24eCVURmRSpAzkOcnRy6SvNjvXMtHMB4VDy34jBtgs1OQIi03eY1BnFcZupDkBxObtetUr5DnDaE2KbvinaSHQH9n1MyM7RVUZLhlZwE/URCLmHttJrPQfmY/DPEQIDAQAB
  -----END PUBLIC KEY-----`,
  // 私钥
  privateKey: `-----BEGIN PRIVATE KEY-----
  MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKaSlcgsppvklmCVyATU0dIKtzEhDA28WdM/Iew532GpdNqnbh4JVRGZFKkDOQ5ydHLpK82O9cy0cwHhUPLfiMG2CzU5AiLTd5jUGcVxm6kOQHE5u161SvkOcNoTYpu+KdpIdAf2fUzIztFVRkuGVnAT9REIuYe20ms9B+Zj8M8RAgMBAAECgYEApd+nBDVinC8fiILfMeB0KQO+tU/BXxRHJtPhhgmDZw+GbA762zJT4jhcmIm7EaXsTFnh4ssP/o9bT23+XD05QoAKfn25Qj4HFVysdcI+KjBfw0XANS3Pe1LvXR7dRpocJNl7kPVbILsu+wmi9w9K19ieBZkxUEs0EVajX8rGf1kCQQDkpodOMrazIJPkbeyJrDVlkgWSI47b7fb6IkTX3ZFzixkZgMFxijgvZbu8vDy0j2xpjcRjw6IfINYSeKQ3r2mDAkEAun8tv2k4xhcZIYdjc4TtNj37qjcjctKYzTXMpptCm4KWEy8kJz6zcx5jbTmyHErdpkD9bPULMWvB47i6IH6E2wJBAM7OgFsOK4lg0eMuOV9cTv+LT1aaqr/pQBWFoVbNpJ0pFo6mklCrf53/GgrfBtkZUCk4fITvkVcuT/FtBLsJARkCQQCrVcYAsTmQe44CCLEsYvXPPHil84wkpCfvd7qxYbh6yCj6LPgI+gjA/S0ZHsVsSreBUvnAjQugdsAlZwPQcIu7AkAgbuP2B/MMbX3HXYKBDjUj7Frpm+1mF0jA+7ebzrH747+2xG1XFVbDcsbaOkHxTTCVwOyK10i8nVe1Ke7tmLG8
  -----END PRIVATE KEY-----
  `,
  SIGN_KEY: '6b50e13',
  // 签名算法
  ALGORITHM: 'SHA256withRSA',
  encrypt: function(data) {
    const jse = new JsEncrypt()
    jse.setPublicKey(this.publicKey)
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    const result = jse.encrypt(data)
    if (typeof (result) === 'boolean') {
      if (!result) {
        Notify({ type: 'warning', message: '公钥不正确,请核对！' })
        return null
      }
    }
    return result
  },
  decrypt: function(data) {
    if (typeof (data) !== 'string') {
      Notify({ type: 'warning', message: '加密数据不正确,请核对！' })
      return null
    }
    const jse = new JsEncrypt()
    jse.setPrivateKey(this.privateKey)
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    const result = jse.decrypt(data)
    return result
  },
  // 私钥签名
  rsaSign: function(plaintext) {
    const signature = new KJUR.crypto.Signature({ 'alg': this.ALGORITHM })
    // 来解析密钥
    const priKey = KEYUTIL.getKey(this.privateKey)
    signature.init(priKey)
    // 传入待签明文
    signature.updateString(plaintext)
    const a = signature.sign()
    // 转换成base64，返回
    return hex2b64(a)
  },
  paramSign(config) {
    var encryptParams = config.params
    var method = config.method
    if (method === 'get') {
      if (config.params != null) {
        encryptParams = config.params
      } else {
        encryptParams = {}
      }
    }
    if (method === 'post') {
      if (config.data != null) {
        encryptParams = config.data
      } else {
        encryptParams = {}
      }
    }

    const values = []
    if (typeof (encryptParams) === 'object') {
      if (Object.prototype.toString.call(encryptParams) === '[object Array]') {
        encryptParams.forEach((item) => {
          if (typeof (item) === 'object') {
            for (const encryptParam in item) {
              if (item[encryptParam] !== undefined) {
                values.push(item[encryptParam])
              }
            }
          } else {
            values.push(item)
          }
        })
      } else {
        for (const encryptParam in encryptParams) {
          if (encryptParams[encryptParam] !== undefined) {
            values.push(encryptParams[encryptParam])
          }
        }
      }
    } else {
      if (encryptParams !== undefined) {
        values.push(encryptParams)
      }
    }
    values.sort()
    values.push(this.SIGN_KEY)

    let s = ''
    values.forEach(function(v, i) {
      if (v !== null) {
        s = s + (v) + ''
      }
    })
    // console.log('参与加密参数:' + s)
    return this.rsaSign(s)
  }
}

Vue.prototype.RSAEncrypt = RSAEncrypt
export default RSAEncrypt
